import process from "node:process";
import Uni from "@dcloudio/vite-plugin-uni";
// @ts-expect-error https://tailwindcss.com
import Tailwindcss from "@tailwindcss/postcss";
// https://uni-helper.js.org/vite-plugin-uni-components
import Components from "@uni-helper/vite-plugin-uni-components";
import { WotResolver } from "@uni-helper/vite-plugin-uni-components/resolvers";
// https://uni-helper.js.org/vite-plugin-uni-layouts
import UniLayouts from "@uni-helper/vite-plugin-uni-layouts";
// https://uni-helper.js.org/vite-plugin-uni-pages
import UniPages from "@uni-helper/vite-plugin-uni-pages";
// https://github.com/uni-ku/bundle-optimizer
import Optimization from "@uni-ku/bundle-optimizer";
import AutoImport from "unplugin-auto-import/vite";
import { defineConfig } from "vite";
import ViteCompression from "vite-plugin-compression";
import ViteRestart from "vite-plugin-restart";
import { UnifiedViteWeappTailwindcssPlugin } from "weapp-tailwindcss/vite";

export default () => {
  // h5 或 app 端不认识 rpx 单位，当运行环境等于 h5 或 app 时，需禁用 rem2rpx
  const UniRemToRpxDisabled = process.env.UNI_PLATFORM === "h5" || process.env.UNI_PLATFORM === "app";

  return defineConfig({
    plugins: [
      UniPages({
        exclude: ["**/components/**/**.*"],
        // 首页需通过.vue文件的<route lang="jsonc" type="home"><route/>，type="home"来设定
        // 非首页的其他页面需通过.vue文件的<route lang="jsonc" type="page"><route/>，type="page"来设定
        // 分包需在此配置，pages 目录为 src/pages，分包目录不能配置在pages目录下
        subPackages: ["src/sources-subpackage", "src/pages-activity", "src/pages-goods", "src/pages-order", "src/pages-user"],
        dts: "uni-pages.d.ts"
      }),
      Components({
        resolvers: [WotResolver()],
        directoryAsNamespace: true,
        dts: "components.d.ts"
      }),
      UniLayouts(),
      Uni(),
      UnifiedViteWeappTailwindcssPlugin({ rem2rpx: true, disabled: UniRemToRpxDisabled }),
      AutoImport({
        imports: [
          "vue",
          "uni-app",
          "pinia",
          {
            from: "wot-design-uni",
            imports: ["useToast", "useMessage", "useCountDown", "useUpload", "CommonUtil"]
          }
        ],
        dts: "auto-import.d.ts",
        vueTemplate: true
      }),
      ViteRestart({
        // 通过这个插件，在修改vite.config.ts文件则不需要重新运行也生效配置
        restart: ["vite.config.[jt]s"]
      }),
      // 分包优化、模块异步跨包调用、组件异步跨包引用
      Optimization({
        enable: {
          "optimization": true,
          "async-import": true,
          "async-component": true
        },
        dts: {
          "enable": true,
          "base": "./",
          // 上面是对类型生成的比较全局的一个配置
          // 下面是对每个类型生成的配置，以下各配置均为可选参数
          "async-import": {
            enable: true,
            base: "./",
            name: "async-import.d.ts",
            path: "./async-import.d.ts"
          },
          "async-component": {
            enable: true,
            base: "./",
            name: "async-component.d.ts",
            path: "./async-component.d.ts"
          }
        },
        logger: false
      }),
      ViteCompression({
        disable: process.env.UNI_PLATFORM !== "h5", // 是否禁用
        threshold: 10240, // 体积大于 threshold 才会被压缩,单位 b
        algorithm: "gzip", // 压缩算法,可选 [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
        ext: ".gz", // 生成的压缩包后缀
        deleteOriginFile: false // 压缩后是否删除源文件
      })
    ],
    css: {
      postcss: {
        plugins: [Tailwindcss()]
      }
    },
    build: {
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
          properties: true,
          keep_fnames: true
        }
      },
      sourcemap: false,
      // 禁用 gzip 压缩大小报告，可略微减少打包时间
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
        }
      }
    }
  });
};
